package com.wukang.photovoltaicinspectionpictures.base

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.launch

/**
 * 基础[Fragment]
 * @param VB [Fragment]布局对应的[ViewBinding]实现类
 * @author wukang
 */
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
    protected val dialogDispose = mutableListOf<Dialog>()

    /**
     * fragment[ViewBinding]实例
     */
    lateinit var mBinding: VB
        private set

    /**
     * 初始化[ViewBinding]实现类
     */
    abstract fun initViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB

    /**
     * 初始化视图
     */
    abstract fun VB.initView()

    /**
     * 初始化界面
     */
    abstract fun initFragment()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // 初始化viewbinding
        mBinding = initViewBinding(inflater, container)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 其他初始化
        mBinding.initView()
        initFragment()

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.DESTROYED) {
                // 在界面销毁时取消dialog，防止内存泄露
                dialogDispose.forEach {
                    if (it.isShowing) {
                        it.cancel()
                    }
                }
            }
        }
    }

    @Suppress("UNCHECKED_CAST")
    protected fun <A : BaseActivity<*, *>> getParentActivity(): A {
        return requireActivity() as A
    }
}